package com.t.bricks.bussiness.service.simplemonitor.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.t.bricks.bussiness.db.dao.simplemonitor.SimpleMonitorDao;
import com.t.bricks.bussiness.model.monitor.AppSystemInfo;
import com.t.bricks.bussiness.model.monitor.MonitorInfo;
import com.t.bricks.bussiness.service.simplemonitor.SimpleMonitorService;
import com.t.bricks.model.MsgEmity;
import com.t.bricks.utils.function.json.JacksonShell;
import com.t.bricks.utils.function.url.URLUtil;

@Service
public class SimpleMonitorServiceImpl implements SimpleMonitorService {
	
	@Autowired
	private SimpleMonitorDao simpleMonitorDao;
	
	/**
	 * 查询监控程序信息
	 * @return
	 */
	@Override
	public MsgEmity search() {
		return simpleMonitorDao.search();
	}
	
	/**
	 * 关闭被监控程序信息
	 * @param sId
	 * @return
	 */
	@Override
	public MsgEmity shutdown(String sId) {
		MsgEmity me = simpleMonitorDao.findById(sId);
		if (!me.isSuccess()) {
			return me;
		}
		
		MonitorInfo monitorInfo = me.getData();
		
		StringBuilder sb = new StringBuilder()
			.append(monitorInfo.getsUrl())
			.append("/shutdown?cloudUser=")
			.append(monitorInfo.getsUser())
			.append("&cloudPass=")
			.append(monitorInfo.getsPass());
			
		String txt = URLUtil.getUrlContent(sb.toString());
		if (null == txt || "".equals(txt)) {
			return MsgEmity.err(8001, "请求操作失败");
		}
		
		me = JacksonShell.toJavaObject(txt, MsgEmity.class);
		if (null == me) {
			return MsgEmity.err(8002, "请求结果转换格式失败");
		}
		
		return me;
	}
	
	/**
	 * 读取指定URL信息
	 * @param monitorInfo
	 * @return
	 */
	@Override
	public MsgEmity loadUrl(MonitorInfo monitorInfo) {
		if (null == monitorInfo) {
			return MsgEmity.err(8001, "参数为空");
		}
		
		String url = new StringBuilder().append(monitorInfo.getsUrl())
				.append("/app/system/inside/info")
				.append("?cloudUser=").append(monitorInfo.getsUser())
				.append("&cloudPass=").append(monitorInfo.getsPass()).toString();
		String temp = URLUtil.getUrlContent(url);
		if (null == temp || "".equals(temp.trim())) {
			return MsgEmity.err(8002, "读取URL信息失败");
		}
		
		MsgEmity me = JacksonShell.toJavaObject(temp, MsgEmity.class);
		if (null == me) {
			return MsgEmity.err(8003, "读取内容不是预期结构");
		}
		
		if (!me.isSuccess()) {
			return me;
		}
		
		AppSystemInfo appSystemInfo = JacksonShell.toJavaObject(me.getData(), AppSystemInfo.class);

		monitorInfo.setsName(appSystemInfo.getAppName());
		monitorInfo.setsStartTime(appSystemInfo.getStartTime());
		monitorInfo.setsSpringStartTime(appSystemInfo.getSpringStartTime());
		
		return MsgEmity.success(monitorInfo, "更新完毕");
	}
	
}
